<!-- 轮播配置页面 -->
<template>
  <div>
    <div class="lunbotu">
      <div>
        <el-button @click="toAdd" class="btn" type="primary" size="mini"
          >新增</el-button
        >
        <el-button @click="toView" type="primary" size="mini">预览</el-button>
      </div>
    </div>
    <!-- 表格 -->
    <div>
      <el-table :data="tableData" stripe style="width: 100%" size="mini">
        <el-table-column type="index" align="center" label="序号" width="100">
        </el-table-column>
        <el-table-column prop="name" align="center" label="轮播图名称">
        </el-table-column>
        <el-table-column prop="introduce" align="center" label="轮播图描述">
        </el-table-column>
        <el-table-column align="center" label="轮播图图片">
          <template slot-scope="scope">
            <el-image
              style="width: 30px; height: 30px"
              :src="scope.row.url"
              :preview-src-list="[scope.row.url]"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column align="center" label="状态">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.status === '正常' ? 'success' : 'danger'"
              >{{ scope.row.status }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              type="text"
              class="warning_info"
              size="small"
              icon="el-icon-edit-outline"
              @click="toEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="text"
              class="red_info"
              size="small"
              icon="el-icon-delete"
              @click="toDelete(scope.row.id)"
              >删除</el-button
            >
            <el-button
              v-if="scope.row.status === '停用'"
              type="text"
              size="small"
              icon="el-icon-key"
              @click="toChange(scope.row)"
              >启用</el-button
            >
            <el-button
              v-if="scope.row.status === '正常'"
              type="text"
              size="small"
              icon="el-icon-lock"
              @click="toChange(scope.row)"
              >停用</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 模态框 -->
    <el-dialog :title="title" :visible.sync="visible" @close="toClose">
      <el-form size="medium" :model="form" :rules="rules" ref="ruleForm">
        <el-form-item prop="name" label="名称" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="url" label="轮播图" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            :action="uploadFileURL"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述" :label-width="formLabelWidth">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="form.introduce"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="toSave">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 模态框预览 -->
    <el-dialog
      :title="title"
      :visible.sync="viewVisible"
      width="80%"
      @close="toClose"
    >
      <div>
        <el-carousel autoplay>
          <el-carousel-item
            v-for="item in tableData"
            v-if="item.status === '正常'"
            :key="item.id"
          >
            <img
              :src="item.url"
              :alt="item.name"
              style="width: 100%; height: 100%"
            />
          </el-carousel-item>
        </el-carousel>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="viewVisible = false"
          >关 闭</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { query, deleteById, saveOrUpdate } from "@/api/carousel";
import { showFileURL, uploadFileURL } from "@/utils/config";

export default {
  data() {
    return {
      showFileURL,
      uploadFileURL,
      tableData: [],
      // 模态框的显示与隐藏
      visible: false,
      viewVisible: false,
      // 表单数据
      form: {},
      // 表单控件标题的宽度
      formLabelWidth: "80px",
      // 模态框的标题
      title: "",
      // 图片url
      imageUrl: "",
      // 校验规则
      rules: {
        name: [
          {
            required: true,
            message: "请上传轮播图名称",
            trigger: "blur",
          },
        ],

        url: [
          {
            required: true,
            message: "请上传轮播图",
            trigger: "change",
          },
        ],
      },
    };
  },
  computed: {},
  methods: {
    async queryData() {
      this.loading = true;
      let temp = {
        // ...this.params,
        // ...this.searchForm,
      };

      // 遍历对象
      for (let key in temp) {
        if (!temp[key]) {
          delete temp[key];
        }
      }
      let res = await query(temp);
      // 加载完毕
      this.loading = false;
      this.tableData = res.data;
      // this.total = res.data.total;
    },
    async toChange(data) {
      if (data.status == "正常") {
        data.status = "停用";
      } else {
        data.status = "正常";
      }
      const temp = {
        status: data.status,
        id: data.id,
      };
      console.log(temp);
      const res = await saveOrUpdate(temp);
      this.queryData();
    },
    toEdit(row) {
      this.queryData();
      // 设置表单数据
      this.form = { ...row };
      this.imageUrl = this.form.url;

      this.title = "编辑轮播图信息";
      this.visible = true;
    },
    toDelete(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteById({ id });
          this.$notify.success({
            title: "成功",
            message: res.success,
          });
          this.queryData();
        })
        .catch(() => {
          this.$notify.info({
            title: "取消",
            message: "已取消删除",
          });
        });
    },
    // 添加按钮事件处理程序
    toAdd() {
      this.queryData();
      // 清空表单数据
      this.form = {};
      this.imageUrl = "";

      this.title = "新增轮播图";
      this.visible = true;
    },
    // 图片上传成功的回调函数
    handleAvatarSuccess(res, file) {
      // console.log(res, "==图片上传成功之后的res");
      this.imageUrl = URL.createObjectURL(file.raw);
      // console.log(this.imageUrl);
      this.form.url = showFileURL + res.data.id;
    },
    // 图片上传之前的回调函数
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 模态框确定按钮事件处理程序
    toSave() {
      // 获取dom的值，对值进行校验 form.name
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          // 校验通过，做自己的业务，保存
          // console.log("校验通过");
          // this.form;
          let res = await saveOrUpdate(this.form);
          // console.log(res, "-----");
          // 提示用户保存成功，刷新表格数据，关闭模态框
          this.$notify.success({
            title: "成功",
            message: res.message,
          });
          this.queryData();
          // this.toClose();
          this.visible = false;
        } else {
          // 校验不通过
          return false;
        }
      });
    },
    // 关闭模态框
    toClose() {
      // 重置表单验证
      this.$refs.ruleForm.resetFields();
    },
    toView() {
      this.title = "大屏预览";
      this.viewVisible = true;
    },
  },
  created() {
    this.queryData();
  },
  mounted() {},
};
</script>
<style lang="scss" scoped>
.lunbotu {
  display: flex;
  height: 40px;
  margin-top: 10px;
  margin-left: 10px;
  .btn {
    margin-right: 10px;
  }
}
</style>